"""
https://www.python-engineer.com/courses/advancedpython/15-thread-vs-process/

Process: An instance of a program(eg a Python interpreter)
+ Takes advantage of multiple CPUS and cores
+ Separate memory space -> Memory is not shared between processes
+ Greate for CPU-bound processing
+ New process is started independently from other process
+ Process are interruptable/killable
+ One GIL for each process -> avoids GIL limitation

- Heavyweight
- Starting a process is slower than starting a thread
- More memory
- IPC (inter-process communication) is complicated

翻译：
+ 在多核CPU使用上有优势
+ 划分独立的内存空间，进程间不共享内存
+ CPU 绑定的进程友好
+ 进程间相互独立
+ 进程是可以打断和kill掉的
+ 每个进程一个全局解释器锁（Global Interpreter Lock，简称 GIL） ->避免GIL限制

算是缺点了
- 比较重，不灵活
- 启动比线程慢
- 占用更多的内存
- 进程间通信较为复杂

Threads: An entity within a process that can be scheduled(also known as "lightweight process")
+ All threads wintin a process share the same memory
+ lightweight
+ Starting a thread is faster than starting a process
+ Great for I/O-bound tasks

- Threading is limited by GIL: Only one thread at a time
- No effect for CPU-bound tasks
- Not interruptable/killable
- Careful with race conditions

翻译：
+ 进程内的所有线程共享内存空间
+ 轻量级
+ 启动比进程要快
+ IO 任务比较友好

- 线程受全局解释器锁（Global Interpreter Lock，简称 GIL）的限制：一次只有一个线程
- 不受CPU 绑定的任务影响
- 不可以被打断和杀死
- 要注意线程竞态条件，避免死锁

task
- 如何使用线程
"""
# 1. 创建和运行多线程
from threading import Thread


def square_numbers():
    for i in range(1000):
        result = i * i


if __name__ == "__main__":
    threads = []
    num_threads = 10

    # create threads and asign a function for each thread
    # 创建多个线程，并且为每个线程分配一个执行函数
    for i in range(num_threads):
        thread = Thread(target=square_numbers)
        threads.append(thread)

    # start all threads
    # 启动每一个线程
    for thread in threads:
        thread.start()

    # wait for all threads to finish
    # block the main thread until these threads are finished
    # 等待所有的线程结束，阻塞主线程直到所有的线程结束
    for thread in threads:
        thread.join()
        print("等待所有的线程结束，阻塞主线程直到所有的线程结束" + thread.name)
